package cn.com.surker.wechat;

import cn.com.surker.common.HttpRequestHelper;
import cn.com.surker.redis.RedisUtils;
import cn.com.surker.spring.SpringContextHolder;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lucky
 * @create 2022年01月18 15:43
 * @desc 微信公众号接口
 */
public class WechatAppletApi {

    private static Logger log = LoggerFactory.getLogger(WechatAppletApi.class);

    /***微信小程序APPID***/
//    public static String applet_appid = "wx2e0f397328100edb";
//    /**微信小程序授权密匙***/
//    public static String applet_secret = "1a05e0c55524e3df44db41d5b9c878fe";
    public static String applet_appid = "wx4315963dacae4c51";
    /**微信小程序授权密匙***/
    public static String applet_secret = "246b50318b11148d05f231db581a2af6";
    /**缓存键**/
    public static String accessTokenKey = "applet_surker_cloud_access_token";
    /**缓存时间**/
    public static Long sessionExpired = 7200L;

    public static void main(String[] args){
//        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + applet_appid + "&secret=" + applet_secret;
//        try {
//            String res = HttpRequestHelper.get(url);
//            System.out.println(res);
//            JSONObject obj = JSONObject.parseObject(res);
//            if(!StringUtils.isNull(obj.getString("access_token"))){
//                log.info("access_token=" + obj.getString("access_token"));
//            } else {
//                log.error("获取微信小程序API token失败：" + res);
//            }
//        } catch (Exception e) {
//            log.error("获取微信小程序API token失败：" + e.getMessage(), e);
//        }
//        String token = "62_KbtFyE6OJutGC6-_GB2jEsILjBdFSPjRKUqnNVIj-dZIDubd5YvJbgr_8lRhklYKyw2zv9dNWNpWrXHX8UDfcJjPpar5Qsh6DUQeVEPLopm_Y6d2J2P4DE9pzTClrghjCj8Y9oYmRGJxHV1yIRSiACAENO";
//        sendTextMessage(token, "oN7Ew40exnl-QoJK8hTyLT8Unykc", "测试万强");
//        sendTextMessage(token, "oN7Ew4yRrLV7nvTXhMnuXGv5T1sY", "测试涛子");
//        sendTextMessage(token, "oN7Ew460fRdr3XSs8WdhL2wT7TpQ", "测试马师傅");
//        sendTextMessage(token, "oN7Ew42tpNOxMdyfY9PgaxC02mv8", "测试刘大爷");
//        sendServiceMessage(token, "oN7Ew40exnl-QoJK8hTyLT8Unykc", "下班申请已通过",
//                "万强请按时下班", "由调度XX审批");
//        sendServiceMessage(token, "oN7Ew4yRrLV7nvTXhMnuXGv5T1sY", "下班申请被拒绝", "涛子请继续加班");
//        sendServiceMessage(token, "oN7Ew460fRdr3XSs8WdhL2wT7TpQ", "下班申请被拒绝", "马师傅请继续加班");
//        sendServiceMessage(token, "oN7Ew42tpNOxMdyfY9PgaxC02mv8", "下班申请被拒绝", "刘大爷请继续加班");
//        sendServiceLineMessage("oN7Ew40exnl-QoJK8hTyLT8Unykc", "车辆入场提醒", "渝A12345",
//                "混凝土运输", "驰旭公司生产1#线", "CS1111", "尊敬的万强师傅您好,您的车辆CS1111正在驰旭公司生产1#线排队中,请您前往停车区等候~！");
//        sendServiceLineMessage("oN7Ew4yRrLV7nvTXhMnuXGv5T1sY", "车辆入场提醒", "渝A12345",
//                "混凝土运输", "驰旭公司生产4#线", "CS1111", "尊敬的罗涛师傅您好,您的车辆CS1111正在驰旭公司生产5#线排队中,请您前往停车区等候~！");
//        sendServiceLineMessage("oN7Ew460fRdr3XSs8WdhL2wT7TpQ", "车辆入场提醒", "渝A12345",
//                "混凝土运输", "生产3#驰旭公司生产3#线", "CS1111", "尊敬的马杰师傅您好,您的车辆CS1111正在驰旭公司生产3#线排队中,请您前往停车区等候~！");
//        sendServiceLineMessage(token, "oN7Ew42tpNOxMdyfY9PgaxC02mv8", "车辆入场提醒", "渝A12345",
//                "混凝土运输", "驰旭公司生产5#线", "CS1111", "尊敬的刘国强师傅您好,您的车辆CS1111正在驰旭公司生产5#线排队中,请您前往停车区等候~！");
        System.out.println(DateUtil.differentMins(DateUtil.convertDate("2022-03-03 13:40:00"), new Date()));

        sendWeightMessage("oN7Ew40exnl-QoJK8hTyLT8Unykc", "车辆过磅完成", "渝A123456",
                "重庆驰瑞", "cs100002", "山石[1-2]", "23.3吨、12吨、32吨", "车辆过磅完成-------------");
    }

    /**
     * 发送微信小程序排队文本消息(服务模板)
     * @param openid openid
     * @param title 标题
     * @param remark 备注
     * @return
     */
    public static Map<String, Object> sendWeightMessage(String openid, String title, String carNo, String supplier,
                                                             String orderId, String material, String weight, String remark) {
//        String token = "68_jQXgnMOYDkZA9AM38Ws92Cqpkj3NlcAVYzbPULKQRFTYqi1AOmwrkkptbkeifGT_u1BjJ7yk6jFH83tzr7NY4h76UdztGiQJKtsLDv6p_JZ1B3LgOoFW3-vSGdMBZPfAHATRH";
        String token = "";
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey)) {
            token = StringUtils.convertString(redisUtils.get(accessTokenKey));
        } else {
            token = getAppletToken();
        }

        if (StringUtils.isNull(token))
            return null;

        String openUrl = "https://weight.chixugroup.com/cloud/weight-detail?openid=" + openid + "&orderId=" + orderId;
        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" + token;
        JSONObject json = new JSONObject();
        JSONObject template = new JSONObject();
        template.put("appid", WechatAccountApi.account_appid);
        template.put("template_id", "tCzdcYlyxgc99p-0Zo3phGkZ7tAmDD9ZWwXOSXjKYHI");
        template.put("url", openUrl);
        template.put("miniprogram", "过磅成功通知");
        if (!StringUtils.isNull(supplier) && supplier.length() > 20)
            supplier = supplier.substring(0, 20);
        if (!StringUtils.isNull(material) && material.length() > 20)
            material = material.substring(0, 20);
        if (!StringUtils.isNull(orderId) && orderId.length() > 20)
            orderId = orderId.substring(0, 20);
        if (!StringUtils.isNull(weight) && weight.length() > 20)
            weight = weight.substring(0, 20);

        JSONObject first = new JSONObject();
        first.put("value", title);
        first.put("color", "#2A82E4");
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", carNo + "(" + DateUtil.convertString(new Date(), "HH时mm分") + ")");
        keyword1.put("color", "#2A82E4");
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", supplier);
        keyword2.put("color", "#2A82E4");
        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", orderId);
        keyword3.put("color", "#2A82E4");
        JSONObject keyword4 = new JSONObject();
        keyword4.put("value", material);
        keyword4.put("color", "#2A82E4");
        JSONObject keyword5 = new JSONObject();
        keyword5.put("value", weight);
        keyword5.put("color", "#2A82E4");
        JSONObject remarkJson = new JSONObject();
        remarkJson.put("value", remark);
        remarkJson.put("color", "#ED5024");
        JSONObject data = new JSONObject();
        data.put("first", first);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("keyword4", keyword4);
        data.put("keyword5", keyword5);
        data.put("remark", remarkJson);
        template.put("data", data);

        json.put("access_token", token);
        json.put("touser", openid);
        json.put("mp_template_msg", template);
//        json.put("access_token", token);
        Map<String, Object> map = new HashMap<>();
        try {
            String res = HttpRequestHelper.senPostJson(url, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(res);
            System.out.println(res);
            log.error("-----发送微信小程序过磅文本消息完成-------：" + res);
            if(obj.getInteger("errcode") == 0){
                map.put("errcode", obj.getString("errcode"));
                map.put("errmsg", obj.getString("errmsg"));
                return map;
            } else if (obj.getInteger("errcode") == 42001 || obj.getInteger("errcode") == 40001
                    || obj.getInteger("errcode") == 41001) {
                redisUtils.remove(accessTokenKey);
                getAppletToken();
                return sendWeightMessage(openid, title, carNo, supplier, orderId, material, weight, remark);
            } else {
                log.error("发送微信小程序过磅文本消息失败：" + res);
                return null;
            }
        } catch (Exception e) {
            log.error("发送微信小程序过磅文本消息失败：" + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发送微信小程序排队文本消息(服务模板)
     * @param openid openid
     * @param title 标题
     * @param remark 备注
     * @return
     */
    public static Map<String, Object> sendServiceLineMessage(String openid, String title, String carNo, String business,
                                                         String line, String code, String remark) {
//        String token = "59_0EfvEo0kVYBn3qYWoSi3POQSeS3EtJ4eeq6BVAtVL_8ZH5H6mY5TvsgFyCA39-8bMPJN9MUc-hVYlvGcIRq1DsXnrXV0s1SDNSajliIDjBWVOuCQh3ss4CZCKv1sgNAhrTZDbpmaC3NC55LoPMLjAIAIFE";
        String token = "";
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey)) {
            token = StringUtils.convertString(redisUtils.get(accessTokenKey));
        } else {
            token = getAppletToken();
        }

        if (StringUtils.isNull(token))
            return null;

        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" + token;
        JSONObject json = new JSONObject();
        JSONObject template = new JSONObject();
        template.put("appid", WechatAccountApi.account_appid);
        template.put("template_id", "2_GMoc389gjc4b9VZ4MiYKQ9OCMC1dMdn-G-vFwA5_I");
        template.put("url", "https://order.chixugroup.com/wechat/driver/vehicle/wait?openid=" + openid);
        template.put("miniprogram", "车辆入场提醒");

        JSONObject first = new JSONObject();
        first.put("value", title);
        first.put("color", "#2A82E4");
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", carNo);
        keyword1.put("color", "#2A82E4");
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", business);
        keyword2.put("color", "#2A82E4");
        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", line);
        keyword3.put("color", "#2A82E4");
        JSONObject keyword4 = new JSONObject();
        keyword4.put("value", code);
        keyword4.put("color", "#2A82E4");
        JSONObject keyword5 = new JSONObject();
        keyword5.put("value", DateUtil.convertString(new Date(), "yyyy年MM月dd日 HH时mm分"));
        keyword5.put("color", "#2A82E4");
        JSONObject remarkJson = new JSONObject();
        remarkJson.put("value", remark);
        remarkJson.put("color", "#ED5024");
        JSONObject data = new JSONObject();
        data.put("first", first);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("keyword4", keyword4);
        data.put("keyword5", keyword5);
        data.put("remark", remarkJson);
        template.put("data", data);

        json.put("access_token", token);
        json.put("touser", openid);
        json.put("mp_template_msg", template);
//        json.put("access_token", token);
        Map<String, Object> map = new HashMap<>();
        try {
            String res = HttpRequestHelper.senPostJson(url, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(res);
            System.out.println(res);
            log.error("-----发送微信小程序排队文本消息完成-------：" + res);
            if(obj.getInteger("errcode") == 0){
                map.put("errcode", obj.getString("errcode"));
                map.put("errmsg", obj.getString("errmsg"));
                return map;
            } else if (obj.getInteger("errcode") == 42001 || obj.getInteger("errcode") == 40001
                    || obj.getInteger("errcode") == 41001) {
                redisUtils.remove(accessTokenKey);
                getAppletToken();
                return sendServiceLineMessage(openid, title, carNo, business, line, code, remark);
            } else {
                log.error("发送微信小程序排队文本消息失败：" + res);
                return null;
            }
        } catch (Exception e) {
            log.error("发送微信小程序排队文本消息失败：" + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发送微信小程序文本消息(异常过磅模板)
     * @param openid
     * @param message 错误消息
     * @param carNo 车牌
     * @param detailUrl
     * @return
     */
    public static Map<String, Object> sendWeightErrorMessage(String openid, String message, String carNo, String detailUrl) {
        String token = "";
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey)) {
            token = StringUtils.convertString(redisUtils.get(accessTokenKey));
        } else {
            token = getAppletToken();
        }

        if (StringUtils.isNull(token))
            return null;

        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" + token;
        JSONObject json = new JSONObject();
        JSONObject template = new JSONObject();
        template.put("appid", WechatAccountApi.account_appid);
        template.put("template_id", "gHZ85X7Aft39Ye-tzikQDRHumMYW5cJFMFCjFLzFB4o");
        template.put("miniprogram", "提示");
        if (!StringUtils.isNull(detailUrl))
            template.put("url", detailUrl);
        else
            template.put("url", "http://weixin.qq.com/download");

        JSONObject first = new JSONObject();
        first.put("value", message);
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", message);
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", carNo);
        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", DateUtil.convertString(new Date(), "yyyy年MM月dd日 HH:mm"));
        JSONObject remark = new JSONObject();
        remark.put("value", message);
        JSONObject data = new JSONObject();
        data.put("first", first);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("remark", remark);
        template.put("data", data);

        json.put("access_token", token);
        json.put("touser", openid);
        json.put("mp_template_msg", template);
//        json.put("access_token", token);
        Map<String, Object> map = new HashMap<>();
        try {
            String res = HttpRequestHelper.senPostJson(url, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(res);
            System.out.println(res);
            if(obj != null && obj.getInteger("errcode") == 0){
                map.put("errcode", obj.getString("errcode"));
                map.put("errmsg", obj.getString("errmsg"));
                return map;
            } else if (obj.getInteger("errcode") == 40001 || obj.getInteger("errcode") == 42001
                    || obj.getInteger("errcode") == 41001) {
                redisUtils.remove(accessTokenKey);
                getAppletToken();
                return sendWeightErrorMessage(openid, message, carNo, detailUrl);
            } else {
                log.error("发送微信小程序文本消息失败：" + res);
                return null;
            }
        } catch (Exception e) {
            log.error("发送微信小程序文本消息失败：" + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发送微信小程序文本消息(服务模板)
     * @param openid openid
     * @param content 内容
     * @param title 标题
     * @param remark 备注
     * @return
     */
    public static Map<String, Object> sendServiceMessage(String openid, String title, String titleColor, String content,
                                                         String contentColor, String remark, String remarkColor, String detailUrl) {
        String token = "";
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey)) {
            token = StringUtils.convertString(redisUtils.get(accessTokenKey));
        } else {
            token = getAppletToken();
        }

        if (StringUtils.isNull(token))
            return null;

        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
        JSONObject json = new JSONObject();
        json.put("template_id", "q3XpNco1duT9Z7H3MbrV3DXLPKR4DKSOqxq-wfeha-0");
        if (!StringUtils.isNull(detailUrl))
            json.put("url", detailUrl);
        else
            json.put("url", "http://weixin.qq.com/download");
//        JSONObject template = new JSONObject();
//        template.put("appid", WechatAccountApi.account_appid);
//        template.put("template_id", "q3XpNco1duT9Z7H3MbrV3DXLPKR4DKSOqxq-wfeha-0");
//        template.put("miniprogram", "提示");
//        if (!StringUtils.isNull(detailUrl))
//            template.put("url", detailUrl);
//        else
//            template.put("url", "http://weixin.qq.com/download");

        JSONObject first = new JSONObject();
        first.put("value", title);
        if (!StringUtils.isNull(titleColor))
            first.put("color", titleColor);
        else
            first.put("color", "#2A82E4");
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", content);
        if (!StringUtils.isNull(contentColor))
            keyword1.put("color", contentColor);
        else
            keyword1.put("color", "#2A82E4");
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", DateUtil.convertString(new Date(), "yyyy年MM月dd日 HH时mm分"));
        keyword2.put("color", "#2A82E4");
        JSONObject remarkJson = new JSONObject();
        remarkJson.put("value", remark);
        if (!StringUtils.isNull(remarkColor))
            remarkJson.put("color", remarkColor);
        else
            remarkJson.put("color", "#ED5024");
        JSONObject data = new JSONObject();
        data.put("first", first);
        data.put("keynote1", keyword1);
        data.put("keynote2", keyword2);
        data.put("remark", remarkJson);
//        template.put("data", data);

        json.put("access_token", token);
        json.put("touser", openid);
        json.put("data", data);
//        json.put("mp_template_msg", template);
//        json.put("access_token", token);
        Map<String, Object> map = new HashMap<>();
        try {
            String res = HttpRequestHelper.senPostJson(url, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(res);
            System.out.println(res);
            if(obj != null && obj.getInteger("errcode") == 0){
                map.put("errcode", obj.getString("errcode"));
                map.put("errmsg", obj.getString("errmsg"));
                return map;
            } else if (obj.getInteger("errcode") == 40001 || obj.getInteger("errcode") == 42001
                    || obj.getInteger("errcode") == 41001) {
                redisUtils.remove(accessTokenKey);
                getAppletToken();
                return sendServiceMessage(openid, title, titleColor, content, contentColor, remark, remarkColor, detailUrl);
            } else {
                log.error("发送微信小程序文本消息失败：" + res);
                return null;
            }
        } catch (Exception e) {
            log.error("发送微信小程序文本消息失败：" + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发送微信小程序文本消息(服务模板)
     * @param openid openid
     * @param content 内容
     * @param title 标题
     * @param remark 备注
     * @return
     */
    public static Map<String, Object> sendWaringServiceMessage(String openid, String title, String content, String name,
                                                         String remark, String detailUrl) {
        String token = "";
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey)) {
            token = StringUtils.convertString(redisUtils.get(accessTokenKey));
        } else {
            token = getAppletToken();
        }

        if (StringUtils.isNull(token))
            return null;

        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" + token;
        JSONObject json = new JSONObject();
        JSONObject template = new JSONObject();
        template.put("appid", WechatAccountApi.account_appid);
        template.put("template_id", "gHZ85X7Aft39Ye-tzikQDRHumMYW5cJFMFCjFLzFB4o");
        template.put("miniprogram", "提示");
        if (!StringUtils.isNull(detailUrl))
            template.put("url", detailUrl);
        else
            template.put("url", "http://weixin.qq.com/download");

        JSONObject first = new JSONObject();
        first.put("value", title.trim());
        first.put("color", "#2A82E4");
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", content.trim());
        keyword1.put("color", "#2A82E4");
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", name.trim());
        keyword2.put("color", "#2A82E4");
        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", DateUtil.convertString(new Date(), "yyyy年MM月dd日 HH时mm分"));
        keyword3.put("color", "#2A82E4");
        JSONObject remarkJson = new JSONObject();
        remarkJson.put("value", remark);
        remarkJson.put("color", "#ED5024");
        JSONObject data = new JSONObject();
        data.put("first", first);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("remark", remarkJson);
        template.put("data", data);

        json.put("access_token", token);
        json.put("touser", openid);
        json.put("mp_template_msg", template);
//        json.put("access_token", token);
        Map<String, Object> map = new HashMap<>();
        try {
            String res = HttpRequestHelper.senPostJson(url, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(res);
            System.out.println(res);
            if(obj != null && obj.getInteger("errcode") == 0){
                map.put("errcode", obj.getString("errcode"));
                map.put("errmsg", obj.getString("errmsg"));
                return map;
            } else if (obj.getInteger("errcode") == 40001 || obj.getInteger("errcode") == 42001
                    || obj.getInteger("errcode") == 41001) {
                redisUtils.remove(accessTokenKey);
                getAppletToken();
                return sendWaringServiceMessage(openid, title, content, name, remark, detailUrl);
            } else {
                log.error("发送微信小程序文本消息失败：" + res);
                return null;
            }
        } catch (Exception e) {
            log.error("发送微信小程序文本消息失败：" + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发送微信小程序文本消息
     * @param openid openid
     * @param content 内容
     * @return
     */
    public static Map<String, Object> sendTextMessage(String token, String openid, String content) {
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey)) {
            token = StringUtils.convertString(redisUtils.get(accessTokenKey));
        } else {
            token = getAppletToken();
        }

        if (StringUtils.isNull(token))
            return null;

        String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token;
        JSONObject json = new JSONObject();
        JSONObject contentJson = new JSONObject();
        contentJson.put("content", content);
        json.put("access_token", token);
        json.put("touser", openid);
        json.put("msgtype", "text");
        json.put("text", content);
//        json.put("access_token", token);
        Map<String, Object> map = new HashMap<>();
        try {
            String res = HttpRequestHelper.senPostJson(url, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(res);
            if(obj != null && obj.getInteger("errcode") == 0){
                JSONObject phoneObj = obj.getJSONObject("phone_info");
                map.put("phoneNumber", phoneObj.getString("phoneNumber"));
                map.put("purePhoneNumber", phoneObj.getString("purePhoneNumber"));
                map.put("countryCode", phoneObj.getString("countryCode"));
                return map;
            } else if (obj.getInteger("errcode") == 40001 || obj.getInteger("errcode") == 42001) {
                redisUtils.remove(accessTokenKey);
                getAppletToken();
                return sendTextMessage(token, openid, content);
            } else {
                log.error("发送微信小程序收车通知文本消息失败：" + res);
                return null;
            }
        } catch (Exception e) {
            log.error("发送微信小程序收车通知文本消息失败：" + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 请求通用印刷体识别
     * @param imgUrl
     * @return
     */
    public static Map<String, Object> printedText(String imgUrl) {
        String token = "";
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey)) {
            token = StringUtils.convertString(redisUtils.get(accessTokenKey));
        } else {
            token = getAppletToken();
        }

        if (StringUtils.isNull(token))
            return null;

        String url = "https://api.weixin.qq.com/cv/ocr/comm?access_token=" + token;
        JSONObject json = new JSONObject();
        json.put("img_url", imgUrl);
        json.put("img", "");
//        json.put("access_token", token);
        Map<String, Object> map = new HashMap<>();
        try {
            String res = HttpRequestHelper.senPostJson(url, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(res);
            log.error("-----请求通用印刷体识别-------：" + res);
            if(obj != null && obj.getInteger("errcode") == 0){
                JSONObject resObj = obj.getJSONObject("phone_info");
                map.put("items", resObj.getString("items"));
                return map;
            } else if (obj.getInteger("errcode") == 40001 || obj.getInteger("errcode") == 42001
                    || obj.getInteger("errcode") == 41001) {
                redisUtils.remove(accessTokenKey);
                getAppletToken();
                return printedText(imgUrl);
            } else {
                log.error("获取微信用户手机号失败：" + res);
                return null;
            }
        } catch (Exception e) {
            log.error("获取微信用户手机号失败：" + e.getMessage(), e);
            return null;
        }
    }


    /**
     *  获取微信用户手机号
     */
    public static Map<String, Object> getPhone(String code) {
        String token = "";
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey)) {
            token = StringUtils.convertString(redisUtils.get(accessTokenKey));
        } else {
            token = getAppletToken();
        }

        if (StringUtils.isNull(token))
            return null;

        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token;
        JSONObject json = new JSONObject();
        json.put("code", code);
//        json.put("access_token", token);
        Map<String, Object> map = new HashMap<>();
        try {
            String res = HttpRequestHelper.senPostJson(url, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(res);
            if(obj != null && obj.getInteger("errcode") == 0){
                JSONObject phoneObj = obj.getJSONObject("phone_info");
                map.put("phoneNumber", phoneObj.getString("phoneNumber"));
                map.put("purePhoneNumber", phoneObj.getString("purePhoneNumber"));
                map.put("countryCode", phoneObj.getString("countryCode"));
                log.error("-----获取微信用户手机号完成-------：" + res);
                return map;
            } else if (obj.getInteger("errcode") == 40001 || obj.getInteger("errcode") == 42001
                    || obj.getInteger("errcode") == 41001) {
                redisUtils.remove(accessTokenKey);
                getAppletToken();
                return getPhone(code);
            } else {
                log.error("获取微信用户手机号失败：" + res);
                return null;
            }
        } catch (Exception e) {
            log.error("获取微信用户手机号失败：" + e.getMessage(), e);
            return null;
        }
    }

    /**
     *  获取微信小程序的临时登录信息
     */
    public static Map<String, Object> getCodeSession(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + applet_appid + "&secret=" + applet_secret + "&js_code="
                + code + "&grant_type=authorization_code";
        Map<String, Object> map = new HashMap<>();
        JSONObject json = new JSONObject();
        try {
            json.put("appid", applet_appid);
            json.put("secret", applet_secret);
            json.put("js_code", code);
            json.put("grant_type", "authorization_code");
            String res = HttpRequestHelper.senPostJson(url, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(res);
            if(obj != null && !StringUtils.isNull(obj.getString("openid"))){
                map.put("openid", obj.getString("openid"));
                map.put("session_key", obj.getString("session_key"));
                map.put("unionid", obj.getString("unionid"));
                return map;
            } else {
                log.error("获取微信小程序临时登录信息失败：" + res);
                return null;
            }
        } catch (Exception e) {
            log.error("获取微信小程序临时登录信息失败：" + e.getMessage(), e);
            return null;
        }
    }

    /**
     *  获取微信小程序的token
     */
    public static String getAppletToken() {
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey)) {
            return StringUtils.convertString(redisUtils.get(accessTokenKey));
        }
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + applet_appid + "&secret=" + applet_secret;
        try {
            String res = HttpRequestHelper.get(url);
            JSONObject obj = JSONObject.parseObject(res);
            if(!StringUtils.isNull(obj.getString("access_token"))){
                log.info("access_token=" + obj.getString("access_token"));
                redisUtils.set(accessTokenKey, obj.getString("access_token"), sessionExpired);
                return obj.getString("access_token");
            } else {
                log.error("获取微信小程序API token失败：" + res);
                return "";
            }
        } catch (Exception e) {
            log.error("获取微信小程序API token失败：" + e.getMessage(), e);
            return "";
        }
    }

}
